﻿using System;
using System.Linq;
using System.Collections.Generic;
using MvcCms.Data;

namespace MvcCms.Service.Code
{
    public static class WeightedContentManager
    {
        private static Random _rnd = new Random();
        public static WeightedContentModule GetNextRandomModuleWithWeightedRatio(IEnumerable<WeightedContentModule> modules)
        {
            int totalWeight = modules.Sum(m => m.Weight);
            int randomNumber = _rnd.Next(0, totalWeight);
            WeightedContentModule selectedWeightedContentModule = null;
            foreach (var module in modules)
            {
                if (randomNumber < module.Weight)
                {
                    selectedWeightedContentModule = module;
                    break;
                }
                randomNumber = randomNumber - module.Weight;
            }
            return selectedWeightedContentModule;
        }
        public static WeightedContentWidget GetNextRandomWidgetWithWeightedRatio(IEnumerable<WeightedContentWidget> widgets)
        {
            int totalWeight = widgets.Sum(m => m.Weight);
            int randomNumber = _rnd.Next(0, totalWeight);
            WeightedContentWidget selectedWeightedContentWidget = null;
            foreach (var widget in widgets)
            {
                if (randomNumber < widget.Weight)
                {
                    selectedWeightedContentWidget = widget;
                    break;
                }
                randomNumber = randomNumber - widget.Weight;
            }
            return selectedWeightedContentWidget;
        }
    }
}